package structure.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author dali
 * @date 2021-07-20 21:20
 * @Description cglib代理
 */

public class UserCglibProxy implements MethodInterceptor {
    private IUserDao userDao;

    public UserCglibProxy(IUserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib代理");
        Object invoke = method.invoke(userDao, objects);
        return invoke;
    }

    public Object getProxyInstance() {
        //创建一个工具类
        Enhancer enhancer=new Enhancer();
        //设置父类
        enhancer.setSuperclass(userDao.getClass());
        //设置回调函数
        enhancer.setCallback(this);
        //返回代理对象
        return enhancer.create();
    }
}
